import * as vscode from "vscode";
import { colors } from "./colors";
export function registerColorBlockDecoration(context: vscode.ExtensionContext) {
  // 定义两种装饰器类型
  const colorBlockDecoration = vscode.window.createTextEditorDecorationType({
    before: {
      contentText: " ",
      width: "10x",
      height: "10x",
      margin: "0 2px 0 0",
    },
    rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
  });

  // 更新装饰器
  const updateDecorations = (editor: vscode.TextEditor) => {
    if (!editor) {
      return;
    }

    const text = editor.document.getText();
    const colorRanges: vscode.DecorationOptions[] = [];

    // 颜色匹配正则（支持 HEX/RGB/HSL）
    const COLOR_REGEX = /ccdd=(\d+)/gi;
    let match;
    while ((match = COLOR_REGEX.exec(text)) !== null) {
      const colorNumber = match[1];
      const color = colors.find((color) => color.number === colorNumber);

      const colorValue = color?.hex;
      if (colorValue === void 0) {
        return;
      }
      const l0 = match[0].length;
      const l1 = match[1].length;

      const startPos = editor.document.positionAt(match.index + l0 - l1);

      // 色块装饰器
      colorRanges.push({
        range: new vscode.Range(startPos, startPos),
        renderOptions: {
          before: {
            contentText: "■",
            color: colorValue,
          },
        },
      });
    }

    editor.setDecorations(colorBlockDecoration, colorRanges);
  };

  // 初始化及事件监听
  let activeEditor = vscode.window.activeTextEditor;
  if (activeEditor) {
    updateDecorations(activeEditor);
  }

  context.subscriptions.push(
    vscode.window.onDidChangeActiveTextEditor((editor) => {
      activeEditor = editor;
      if (editor) {
        updateDecorations(editor);
      }
    }),
    vscode.workspace.onDidChangeTextDocument((event) => {
      if (activeEditor && event.document === activeEditor.document) {
        updateDecorations(activeEditor);
      }
    })
  );
}
